/*
 * Copyright 2009 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.appengine.demos.oauth;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Handler for OAuth callback for contacts approval.
 */
public class FetchContactsCallbackServlet extends HttpServlet {
  private final ContactsFetcher contactsFetcher = new ContactsFetcher();

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
      IOException {
    ContactsTemplates.setNoCache(resp);
    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();
    if (user == null) {
      resp.sendRedirect(userService.createLoginURL(req.getRequestURL().toString()));
      return;
    }
    OAuthFetchResponse contactsResponse =
        contactsFetcher.fetchContacts(req, resp, getCurrentUrl(req));
    if (contactsResponse.getOAuthError() == null) {
      ContactsTemplates.showContactsPage(req, resp, contactsResponse, "/contacts_ok.jsp");
    } else {
      ContactsTemplates.showContactsPage(req, resp, contactsResponse, "/contacts_error.jsp");
    }
  }
  
  private String getCurrentUrl(HttpServletRequest req) {
    StringBuffer current = req.getRequestURL();
    if (req.getQueryString() != null) {
      current.append('?');
      current.append(req.getQueryString());
    }
    return current.toString();
  }
}
